<?php 


defined( '_JEXEC' ) or die( 'Restricted Access' );
jimport( 'joomla.application.component.model' );
require_once (JPATH_COMPONENT_ADMINISTRATOR . DS . 'images.shop.php');
require_once (JPATH_COMPONENT_ADMINISTRATOR . DS . 'config.shop.php');
class ShopModelNew_Good extends JModel
{	
	var $_data;
    var $_id;
	
	
	
	function setId($id)
    {
        $this->_id = $id;
        $this->_data = null;
    }

	function getData()
	{
			if(empty($this->_data))
			{
				$query = "SELECT * 
						  FROM #__shop_prod
						  WHERE id=".$this->_id;
				$this->_db->setQuery($query);
				$this->_data = $this->_db->loadObject();
			}
			return $this->_data;
	}
	
	function store($data)
	{
		ini_set('max_execution_time',60);
		ini_set('memory_limit','64M');
		
		$mainframe = &JFactory::getApplication();
		$db= &JFactory::getDBO();
		$query = "SELECT * 
						  FROM #__shop_prod
						  WHERE id=".$data[id];
		$db->setQuery($query);
		$is_new = $db->loadResult();
		$good = $db->loadObject();
		
		if($data[on_main] != 1)
			$data[on_main] = 0;
		if($data[update_description] != 1)
			$data[update_description] =0;
			
			
		
		$image_name = $this->_img($_FILES["main_img"]["tmp_name"],$_FILES['main_img']['name'],$good->main_img);
		// получаем из базы все доп изображения
		if($good->add_img != '')
			$addit = explode(';',$good->add_img);
		
		
		foreach($_FILES['additional_image']["tmp_name"] as $key=>$additional){
			if($_FILES['additional_image']['name'][$key] != '')
				$addit[] = $this->_img($additional,$_FILES['additional_image']['name'][$key],'');
		}
		$addit = implode(';',$addit);
		
		$query = "SELECT * FROM #__shop_fields WHERE published=1 AND all_cats=1 AND system=1";
		$db->setQuery($query);
		$all_fields = $db->loadObjectList();
		
		
		$data[additional_text] = JRequest::getVar( 'additional_text', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data[additional_text] = str_ireplace('<BR mce_bogus="1">','',$data[additional_text]);
		
			
		
		$data[description] = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data[description] = str_ireplace('<BR mce_bogus="1">','',$data[description]);
		$data[description] = str_ireplace('white-space: nowrap;','',$data[description]);
		$data[price] = preg_replace('#[^0-9]#','', $data[price]); 
	//	$data[cat_id] = $data['cat_'.$data[sec_id]];
		$alias = str_ireplace(' ','-',$this->_translate(mysql_real_escape_string(preg_replace('#[\\.,;:-]*#Uis', '', rtrim(mysql_real_escape_string($data[name]))))));
		
		if($is_new!=null)
			$query = "SELECT alias FROM #__shop_prod WHERE alias='".$alias."' AND id!=".$good->id;
		else
			$query = "SELECT alias FROM #__shop_prod WHERE alias='".$alias."'";
		$db->setQuery($query);
		$alias_exist = $db->loadResult() !== null;
		$i = 1;
		while($alias_exist){
			$alias = str_ireplace(' ','-',$this->_translate(mysql_real_escape_string(preg_replace('#[\\.,;:-]*#Uis', '', rtrim(mysql_real_escape_string($data[name]))))))."_".$i;	
			if($is_new!=null)
				$query = "SELECT alias FROM #__shop_prod WHERE alias='".$alias."' AND id!=".$good->id;
			else
				$query = "SELECT alias FROM #__shop_prod WHERE alias='".$alias."'";
			$db->setQuery($query);
			$alias_exist = $db->loadResult() !== null;
			$i++;					
		}
		
		if((int)$data[dublicated_cat] != (int)$data[cat_id])
				$dublicated_cat = (int)$data[dublicated_cat];
			else
				$dublicated_cat = 0;
		
		$sklad_sum = 0;
		foreach($data['sklad_1'] as $k=>$value){
				if($value > 0 ){
					$sklad_sum = 1;
					break;
				}
			}
		
		
		if($is_new != null)
		{
			
			$query = "UPDATE #__shop_prod SET name='".mysql_real_escape_string($data[name])."',cat_id='".mysql_real_escape_string($data[cat_id])."',dublicated_cat=".$dublicated_cat.",articul='".mysql_real_escape_string($data[articul])."',price='".mysql_real_escape_string($data[price])."',description='".mysql_real_escape_string($data[description])."',main_img='".mysql_real_escape_string($image_name)."',published='".mysql_real_escape_string($data[published])."',material='".mysql_real_escape_string($data[material])."',manufact='".mysql_real_escape_string($data[manufact])."',add_img='".$addit."',old_price='".mysql_real_escape_string($data[old_price])."',additional_text='".mysql_real_escape_string($data[additional_text])."',on_main=".$data[on_main].",update_description=".$data[update_description].",alias='".$alias."',sklad_sum='".$sklad_sum."',metatitle='".mysql_real_escape_string($data[metatitle])."' WHERE id=".$data[id];
			$db->setQuery($query);
			$db->query();
			/* изменяем название ЧПУ ссылки товара */
			$db->setQuery("SELECT * FROM #__redirection WHERE locate('".$good->alias."',oldurl)>0");
			$redirection = $db->loadObjectList();
			foreach($redirection as $redirect){
				$db->setQuery("UPDATE #__redirection SET oldurl='".str_ireplace($good->alias,$alias,$redirect->oldurl)."' WHERE id=".$redirect->id);
				$db->query();
			}	
			
			
		}
		else
		{
			$query = "INSERT INTO #__shop_prod (name,cat_id,dublicated_cat,articul,price,old_price,description,main_img,published,material,manufact,add_img,additional_text,on_main,alias,sklad_sum,metatitle) VALUES ('".mysql_real_escape_string($data[name])."','".mysql_real_escape_string($data[cat_id])."',".$dublicated_cat.",'".mysql_real_escape_string($data[articul])."','".mysql_real_escape_string($data[price])."','".mysql_real_escape_string($data[old_price])."','".mysql_real_escape_string($data[description])."','".mysql_real_escape_string($image_name)."','".mysql_real_escape_string($data[published])."','".mysql_real_escape_string($data[material])."','".mysql_real_escape_string($data[manufact])."','".$addit."','".mysql_real_escape_string($data[additional_text])."','".$data[on_main]."','".$alias."',sklad_sum='".$sklad_sum."','".mysql_real_escape_string($data[metatitle])."')";
			$db->setQuery($query);
			$db->query();
			
			$data[id] = $db->insertid();
			
		}
		
		$db->setQuery("SELECT id,products FROM #__shop_keywords WHERE published=1");
		$keywords = $db->loadObjectList();
		
		foreach($keywords as $keyword){
			if(!isset($data[keyword][$keyword->id]) && stripos($keyword->products,'<id>'.$data[id].'</id>') !== FALSE){
				$db->setQuery("UPDATE #__shop_keywords SET products='".str_ireplace('<id>'.$data[id].'</id>','',$keyword->products)."' WHERE id=".$keyword->id);
				$db->query();
			}
			else
				if(isset($data[keyword][$keyword->id]) && stripos($keyword->products,'<id>'.$data[id].'</id>') === FALSE){
					$db->setQuery("UPDATE #__shop_keywords SET products='".$keyword->products.'<id>'.$data[id].'</id>'."' WHERE id=".$keyword->id);
					$db->query();
				}
		}
		
		
		
		$query = "SELECT * FROM #__shop_prod WHERE id=".$data[id];
		$db->setQuery($query);
		$new_good = $db->loadObject();
		
		// обновляем табличку onmain в зависимости от того какое значение присваивается
		
		// если картинка на главной не была установлена, но ее установили
		if(($good->on_main == 0  && $data[on_main]==1) || ($data[on_main] == 1 && $is_new ==null)){
			$row = $this->getTable('onmain', 'ShopTable');
			$row->bind($data);
			$ordering = $row->getNextOrder();
			$query = "INSERT INTO #__shop_onmain (prod_id,ordering) VALUES (".$data[id].",".$ordering.")";
			$db->setQuery($query);
			$db->query();
			// создаем картинку 160х240 пх максимум
			dgImageCreate(JPATH_SITE . '/components/com_shop/images/originals/'.$new_good->main_img, JPATH_SITE . '/components/com_shop/images/main_page' . DS . $new_good->main_img, 160, 240, '95', '1');
			
		}
		if($good->on_main == 1 &&  $data[on_main]==1 && $_FILES["main_img"]["tmp_name"] != ''){
			// если обновилось изображение товара и товар на главной , то обновляем и изображение на главной
			@unlink(JPATH_SITE . '/components/com_shop/images/main_page'. DS . $good->main_img);
			dgImageCreate(JPATH_SITE . '/components/com_shop/images/originals/'.$new_good->main_img, JPATH_SITE . '/components/com_shop/images/main_page' . DS . $new_good->main_img, 160, 240, '95', '1');
		}
		// если до этого картинка на главной была установлена , но ее оттуда удаляют
		if($data[on_main] != $good->on_main && $data[on_main]==0 && $is_new != null){
			$query = "DELETE FROM #__shop_onmain WHERE prod_id=".$data[id];
			$db->setQuery($query);
			$db->query();
			@unlink(JPATH_SITE . '/components/com_shop/images/main_page'. DS . $good->main_img);
		}
		
		foreach($all_fields as $key=>$field){
		/*
			if($is_new != null){
				$query = "DELETE FROM #__shop_fields_values WHERE object_id=".$data[id]." AND field_id=".$field->id;
				$db->setQuery($query);
				$db->query();
			}
		*/
			foreach($data['value_'.$field->id] as $k=>$value){
				if($value != ''){
					$sklad = $data['sklad_'.$field->id][$k];
					if(isset($data['old_field_id_'.$field->id][$k]))
						$query = "UPDATE #__shop_fields_values SET value='".mysql_real_escape_string($value)."',sklad='".mysql_real_escape_string($sklad)."' WHERE id=".$data['old_field_id_'.$field->id][$k];
					else
						$query = "INSERT INTO #__shop_fields_values (field_id,object_id,value,sklad) VALUES ('".$field->id."','".$data[id]."','".mysql_real_escape_string($value)."','".mysql_real_escape_string($sklad)."')";
					$db->setQuery($query);
					$db->query();
				}
				else
					if(isset($data['old_field_id_'.$field->id][$k])){
						$query = "DELETE FROM #__shop_fields_values WHERE id=".$data['old_field_id_'.$field->id][$k];
						$db->setQuery($query);
						$db->query();
					}
			}
		}

		return true;	
	}
	
	
	function _img($image,$image_name,$original_name,$on_main = false)
	{
		
            $oConf = ShopController::conf();
		$mainframe = &JFactory::getApplication();
		if($image != '')
		{
			if($original_name != ''){
				@ unlink(JPATH_SITE . '/components/com_shop/images/originals'. DS . $original_name);
				@ unlink(JPATH_SITE . '/components/com_shop/images/small'. DS . $original_name);
				@ unlink(JPATH_SITE . '/components/com_shop/images/big'. DS . $original_name);
				
			}
			
			$imagetype = array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG');
			$imginfo = getimagesize($image);
			$imginfo[2] = $imagetype[$imginfo[2]];
			if (!$imginfo[3])
			{
				$mainframe->redirect("index.php?option=com_shop&view=goods", 'Неправильное имя файла изображения!','error');
			}  
			else
				if ($imginfo[2] != 'GIF' && $imginfo[2] != 'JPG' && $imginfo[2] != 'PNG') 
				{
				  $mainframe->redirect("index.php?option=com_shop&view=goods", 'Неверный тип изображения !','error');
				}
				else
				  $image_name = $this->_dgImgId($imginfo[2]);
			$width = $imginfo[0];
			$height = $imginfo[1];
			
			
			copy($image, JPATH_SITE . '/components/com_shop/images/originals' . DS . $image_name);
			if($oConf->small_width > 200 && $oConf->small_height > 200)
				dgImageCreate($image, JPATH_SITE . '/components/com_shop/images/small' . DS . $image_name, $oConf->small_width, $oConf->small_height, '95', '1');
			else
				dgImageCreate($image, JPATH_SITE . '/components/com_shop/images/small' . DS . $image_name, '200', '200', '95', '1');
			dgImageCreate($image, JPATH_SITE . '/components/com_shop/images/big' . DS . $image_name, '160', '280', '95', '1');
			
					
			
		}
		else
			$image_name = $original_name;
		
		return $image_name;
	}
	
	function _translate($title)
	{
		$tbl= array(
			'а'=>'a', 'б'=>'b', 'в'=>'v', 'г'=>'g', 'д'=>'d', 'е'=>'e', 'ж'=>'g', 'з'=>'z',
			'и'=>'i', 'й'=>'y', 'к'=>'k', 'л'=>'l', 'м'=>'m', 'н'=>'n', 'о'=>'o', 'п'=>'p',
			'р'=>'r', 'с'=>'s', 'т'=>'t', 'у'=>'u', 'ф'=>'f', 'ы'=>'i', 'э'=>'e', 'А'=>'A',
			'Б'=>'B', 'В'=>'V', 'Г'=>'G', 'Д'=>'D', 'Е'=>'E', 'Ж'=>'G', 'З'=>'Z', 'И'=>'I',
			'Й'=>'Y', 'К'=>'K', 'Л'=>'L', 'М'=>'M', 'Н'=>'N', 'О'=>'O', 'П'=>'P', 'Р'=>'R',
			'С'=>'S', 'Т'=>'T', 'У'=>'U', 'Ф'=>'F', 'Ы'=>'I', 'Э'=>'E', 'ё'=>"yo", 'х'=>"h",
			'ц'=>"ts", 'ч'=>"ch", 'ш'=>"sh", 'щ'=>"shch", 'ъ'=>"", 'ь'=>"", 'ю'=>"yu", 'я'=>"ya",
			'Ё'=>"YO", 'Х'=>"H", 'Ц'=>"TS", 'Ч'=>"CH", 'Ш'=>"SH", 'Щ'=>"SHCH", 'Ъ'=>"", 'Ь'=>"",
			'Ю'=>"YU", 'Я'=>"YA", ' '=>"-", '('=>'', ')'=>'', ','=>'', '.'=>''
			);

		$translate = mb_strtolower(strtr($title, $tbl));
		return $translate;
	}
	
	function _dgImgId($imgext) // функция генерирования имени изображения
	{
		return substr(strtoupper(md5(uniqid(time()))), 5, 12).'.' . strtolower($imgext);
	}
}
?>